﻿using System.Diagnostics;
namespace CloseProgramByPort
{
    public class ProgramUtils
    {
        public static void KillProgramByPid(int pid)
        {
            try
            {
                Process process = Process.GetProcessById(pid);
                process.Kill();
            }
            catch (ArgumentException)
            {
                throw new Exception($"没有找到 PID 为 {pid} 的进程。");
            }
            catch (InvalidOperationException ex)
            {
                throw new Exception($"无法操作该进程：{ex.Message}");
            }
            catch (Exception ex)
            {
                throw new Exception($"发生错误：{ex.Message}");
            }
        }

        // 根据端口查找 PID
        public static List<int> GetProcessIdsByPort(int port)
        {
            var processStartInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                Arguments = $"/c netstat -ano | findstr :{port}",
                RedirectStandardOutput = true,
                RedirectStandardError = true, // 捕获错误流
                UseShellExecute = false,
                CreateNoWindow = true
            };

            List<int> pids = new List<int>();

            using (var process = Process.Start(processStartInfo))
            {
                if (process == null) return pids;

                string output = process.StandardOutput.ReadToEnd();
                string error = process.StandardError.ReadToEnd(); // 获取错误输出用于调试
                Console.WriteLine("Error Output: " + error); // 调试用，可删除

                string[] lines = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string line in lines)
                {
                    string[] parts = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length >= 5)
                    {
                        string state = parts[3].Trim().ToUpperInvariant();
                        // 支持中英文 LISTENING/侦听 状态
                        if (state == "LISTENING" || state.Contains("侦听"))
                        {
                            // 格式如 0.0.0.0:80 或 [::]:8080
                            string localAddressPort = parts[1];
                            // 提取端口号
                            if (localAddressPort.Contains(":"))
                            {
                                string[] addressParts = localAddressPort.Split(':');
                                if (int.TryParse(addressParts[^1], out int tPort))
                                {
                                    if (port == tPort && int.TryParse(parts[^1], out int pid))
                                    {
                                        pids.Add(pid);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return pids.Distinct().ToList();
        }
    }
}
